#!/usr/local/bin/perl -w
use strict;
use utf8;
use lib '../lib';


use NG::Sys::App 'NG::Sys::Loop::Run';
use NG::Sys::Datetime;
use Time::HiRes qw(gettimeofday);
use Data::Dumper;
use JSON::XS;

my $app = new NG::Sys::App(logger=>"screen");

my %valid = map { $_=>1 } qw(get try free weak);

$app->die_to_logger;
$app->warn_to_logger;

$app->run();

sub on_process {
	my $app = shift;
	my $key = $app->arg->{key};
	if($app->arg->{local}){
		while(1){
			printf "local: %.2f\n",bm_local(10000,$key);
			#print Dumper(decode_json($app->local_block->stat));
			#printf "global: %.2f\n",bm_global(10000,$key);
			#print Dumper(decode_json($app->global_block->stat));
		}
	}else{
		while(1){
			#printf "local: %.2f\n",bm_local(10000,$key);
			#print Dumper(decode_json($app->local_block->stat));
			printf "global: %.2f\n",bm_global(10000,$key);
			#print Dumper(decode_json($app->global_block->stat));
		}
	}
}


sub on_process1 {
	my $app = shift;
	while(my $str = <STDIN>){
		$str =~ s/\s+$//;
		my($cmd,$key) = split /\s+/,$str;
		unless($cmd && $valid{$cmd}){
			print "bad cmd\n";
			next;
		}
		if($app->block->$cmd("test1")){
			print unixtime2hms(),": '$cmd' ok\n";
		}else{
			print "fail\n";
		}
	}
}

sub bm_local {
	my $count = shift;
	my $key = shift || "test1";
	my $r0 = gettimeofday;
	for(1..$count){
		$app->local_block->get($key);
		$app->local_block->free($key);
	}
	my $r1 = gettimeofday;
	return $count/($r1-$r0);
}
sub bm_global {
	my $count = shift;
	my $key = shift || "test1";
	my $r0 = gettimeofday;
	for(1..$count){
		$app->global_block->get($key);
		$app->global_block->free($key);
	}
	my $r1 = gettimeofday;
	return $count/($r1-$r0);
}
